#include <tipos.h>
#include <syscalls.h>
#include <fs.h>
#include <string.h>
#include <stdio.h>
#include <i386.h>

int
sprintf_internal(char * buffer, char * format, uint_32 * stack);

static FILE_DESC cd; 


void
stdio_init()
{
	cd = open("/console", FS_OPEN_RDWR);
	stdio_print("Ready!\n");
}

void
stdio_close()
{
	flush(cd);
}

void
stdio_print(const char *s) {
 	write(cd, s, strlen(s));
}

void
stdio_printf(char* format, ...) {
	uint_32 *param;
	
	static char * buffer = NULL;
	
	if (buffer == NULL)
		buffer = palloc();
	

	param = (uint_32 *) rebp();
	param += 3;
	
	sprintf_internal(buffer, format, param);
	stdio_print(buffer);
}

int
stdio_readline( char * buffer, uint_32 size )
{
	char k;
	int c;

	c = 0;
	k = 'a';

	while (k != '\n' && c < size) {
		read(cd, &k, 1);

		switch(k) {
			case '\n':
				buffer[c] = '\0';
				break;
			case '\b':
				if (c > 0) {
					write(cd, &k, 1);
					c--;
				}
				break;
			default:
				if (c < 32) {
					write(cd, &k, 1);
					buffer[c] = k;
					c++;
				}
		}
	}
	
	return c;
}

void
stdio_wait()
{
	char c;
	stdio_readline(&c,1);
}
